package ThreadingSafety;

import java.util.concurrent.locks.Condition;;
import java.util.concurrent.locks.ReentrantLock;

/**
 *     synchronized 是搭配 wait/notify 实现等待通知机制的.唤醒操作是随机唤醒一个等待的线程.
 *     ReentrantLock 搭配Condition类实现的.唤醒操作是可以指定唤醒哪个等待的线程的.
 *
 *     代码测试 ReentrantLock 搭配Condition类实现的等待通知机制.
 *
 *     Condition内部维护了一个等待队列，当线程调用condition.await()时，
 *     会将当前线程封装成一个Node并添加到队列中，然后释放锁，供其他线程竞争。
 *
 *    调用condition.signal()时，会唤醒等待队列中等待时间最长的节点(头节点)，
 *    并将该节点移出队列，该节点中的线程会继续竞争锁，执行逻辑代码。
 */

public class TestDemo28Child {
    //库存数
    private volatile int goodsCount = 0;
    //锁
    private final ReentrantLock lock = new ReentrantLock();
    //生产者condition
    private final Condition producerCondition = lock.newCondition();
    //消费者condition
    private final Condition consumerCondition = lock.newCondition();

    public class Producer extends Thread {
        volatile boolean flag = true;
        @Override
        public void run() {
            while (flag) {
                try {
                    lock.lock();
                    //最大库存数
                    int MAX_COUNT = 1000;
                    if (goodsCount >= MAX_COUNT) {
                        //库存满 停止生产 通知消费者消费
                        consumerCondition.signalAll();
                        producerCondition.await();
                    }
                    else {
                        Thread.sleep(5);
                        System.out.println("生产: "+(++goodsCount)  + " " + Thread.currentThread().getName());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    private class Consumer extends Thread{
        @Override
        public void run() {
            while (true) {
                try {
                    lock.lock();
                    if (goodsCount <= 0) {
                        //没有库存，停止消费 通知生产者生产
                        //System.err.println("没有库存了..");
                        producerCondition.signalAll(); //唤醒全部等待在Condition上的线程
                        //producerCondition.signal();  //唤醒一个等待在Condition上的线程
                        consumerCondition.await();  // 线程进入阻塞状态.
                    }else {
                        Thread.sleep(5);
                        System.out.println("消费: " + (--goodsCount) + " " + Thread.currentThread().getName());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        TestDemo28Child demo = new TestDemo28Child();
        //创建一个生产者
        demo.new Producer().start();

        //创建5个消费者
        for (int i = 0; i < 5; i++) {
            demo.new Consumer().start();
        }
    }
}

